package com.dson.interceptor;

import com.dson.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        //如果session中有用户数据，则继续向下执行
        if (user != null ) {
            return true;
        } else {
            //获取密码后进行判断
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            if(username == null || password == null){
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
//                response.sendRedirect("/resume/login");
                return false;
            }

            if ( username.equals("admin")  && password.equals("admin")) {
                //将用户对象添加到Session中
                User user1 = new User();
                user1.setName(username);
                user1.setPassword(password);
                session.setAttribute("USER_SESSION", user1);
                //重定向到主页面的跳转方法
//                request.getRequestDispatcher("/resume/queryAll").forward(request, response);
                return true;
            }else{
                request.setAttribute("msg", "用户名或密码错误，请重新登录！");
                // 不符合条件则进行跳转
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
                return false;
            }
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
